import { memo, useEffect, useMemo, useState } from "react";
import {
  Button,
  Col,
  Divider,
  Drawer,
  Form,
  Input,
  message,
  Row,
  Select,
  Spin,
} from "antd";
import {
  useGetOrganizationInfo_service,
  useUpdateOrg_service,
} from "../../../../service/organization";
import EditStyle from "./style";
import UploadV2 from "../../../../baseUI/uploadV2";
import { OrganizationType_mutation } from "../../../../types/organization";

const Edit = memo(
  (props: {
    open: boolean;
    setOpenState: (value: boolean) => void;
    id: string;
    refechOrgs: () => void;
  }) => {
    const [open, setOpen] = useState(false);
    const { data, loading, refetch } = useGetOrganizationInfo_service(props.id);
    const { handleEdit, editLoading } = useUpdateOrg_service();
    const [form] = Form.useForm();
    const initValue = useMemo(() => {
      return data
        ? {
            ...data,
            tags: (data?.tags as string)?.split("，"),
            logo: [{ url: data.logo }],
            identityCardBackImg: [{ url: data.identityCardBackImg }],
            identityCardFrontImg: [{ url: data.identityCardFrontImg }],
            businessLicense: [{ url: data.businessLicense }],
          }
        : {};
    }, [data]);
    const onFinishEdit = () => {
      // 校验表单数据
      void form
        .validateFields()
        .then((value: OrganizationType_mutation) => {
          const editData: {
            identityCardBackImg: string;
            businessLicense: string;
            address?: string;
            orgOtherImg: { url: string }[];
            orgRoomImg: { url: string }[];
            latitude?: string;
            description?: string;
            tags: string;
            orgFrontImg: { url: string }[];
            identityCardFrontImg: string;
            name?: string;
            logo: string;
            tel?: string;
            id?: string;
            longitude?: string;
          } = {
            ...value,
            logo: value.logo?.[0].url as string,
            tags: value.tags.join("，") as string,
            identityCardBackImg: value.identityCardBackImg?.[0].url as string,
            identityCardFrontImg: value.identityCardFrontImg?.[0].url as string,
            businessLicense: value.businessLicense?.[0].url as string,
            orgFrontImg: value.orgFrontImg?.map((item) => ({
              url: item.url,
            })) as { url: string }[],
            orgRoomImg: value.orgRoomImg?.map((item) => ({
              url: item.url,
            })) as { url: string }[],
            orgOtherImg: value.orgOtherImg?.map((item) => ({
              url: item.url,
            })) as { url: string }[],
          };

          void handleEdit(props.id, editData)
            .then(() => {
              props.refechOrgs();
              void refetch({ id: props.id });
            })
            .catch(() => {
              void message.error("请检查表单！");
            });
        })
        .catch(() => {
          void message.error("表单校验未通过请检查！");
        });
    };
    useEffect(() => {
      if (props.open) {
        setOpen(true);
      }
      return () => {
        form.resetFields();
      };
    }, [props.open]);

    const closeDrawer = () => {
      setOpen(false);
      props.setOpenState(false);
    };

    return (
      <EditStyle>
        {loading ? (
          <Spin />
        ) : (
          <Drawer
            title="门店详情"
            placement="right"
            width="70vw"
            onClose={closeDrawer}
            open={open}
            footerStyle={{ textAlign: "right" }}
            footer={
              <Button
                loading={editLoading}
                type="primary"
                onClick={onFinishEdit}
              >
                保存
              </Button>
            }
          >
            <Form
              form={form}
              initialValues={initValue}
              layout="vertical"
              scrollToFirstError
              preserve={false}
            >
              <Row className="row" gutter={20}>
                <Col span={10}>
                  <Form.Item
                    style={{ width: "100%" }}
                    label="logo"
                    name="logo"
                    rules={[{ required: true }]}
                    shouldUpdate
                  >
                    <UploadV2
                      label="替换 Logo"
                      id={props.id}
                      imgCropAspect={1}
                      maxCount={1}
                    />
                  </Form.Item>
                </Col>
                <Col span={14}>
                  <Form.Item
                    style={{ width: "100%" }}
                    label="名称"
                    name="name"
                    rules={[{ required: true }]}
                    shouldUpdate
                  >
                    <Input placeholder="请输入门店名称" />
                  </Form.Item>
                </Col>
              </Row>
              <Row className={"row"} gutter={20}>
                <Col span={11}>
                  <Form.Item
                    label="标签"
                    name="tags"
                    rules={[{ required: true }]}
                    shouldUpdate
                  >
                    <Select
                      mode="tags"
                      style={{ width: "100%" }}
                      placeholder="请输入标签"
                    />
                  </Form.Item>
                </Col>
                <Col span={5}>
                  <Form.Item
                    label="手机号"
                    name="tel"
                    shouldUpdate
                    rules={[
                      { required: true },
                      {
                        pattern: /^1\d{10}$/,
                        message: "手机号格式错误！",
                      },
                    ]}
                  >
                    <Input placeholder="请输入手机号" />
                  </Form.Item>
                </Col>
                <Col span={4}>
                  <Form.Item
                    label="经度"
                    name="longitude"
                    rules={[{ required: true }]}
                    shouldUpdate
                  >
                    <Input placeholder="请输入经度" />
                  </Form.Item>
                </Col>
                <Col span={4}>
                  <Form.Item
                    label="纬度"
                    name="latitude"
                    rules={[{ required: true }]}
                    shouldUpdate
                  >
                    <Input placeholder="请输入纬度" />
                  </Form.Item>
                </Col>
              </Row>
              <Form.Item
                label="地址"
                name="address"
                rules={[{ required: true }]}
                shouldUpdate
              >
                <Input placeholder="请输入地址" />
              </Form.Item>
              <Form.Item
                label="门店简介"
                name="description"
                rules={[{ required: true }]}
                shouldUpdate
              >
                <Input.TextArea
                  maxLength={500}
                  rows={5}
                  className="textArea"
                  allowClear
                  showCount
                />
              </Form.Item>
              <Row className={"row"} gutter={20}>
                <Col span={8}>
                  <Form.Item
                    style={{ width: "100%" }}
                    label="营业执照"
                    name="businessLicense"
                    rules={[{ required: true }]}
                    shouldUpdate
                  >
                    <UploadV2
                      label="替换营业执照"
                      maxCount={1}
                      imgCropAspect={3 / 2}
                      id={props.id}
                    />
                  </Form.Item>
                </Col>
                <Col span={8}>
                  <Form.Item
                    style={{ width: "100%" }}
                    label="身份证正面"
                    name="identityCardFrontImg"
                    rules={[{ required: true }]}
                    shouldUpdate
                  >
                    <UploadV2
                      label="替换身份证"
                      maxCount={1}
                      imgCropAspect={3 / 2}
                      id={props.id}
                    />
                  </Form.Item>
                </Col>
                <Col span={8}>
                  <Form.Item
                    style={{ width: "100%" }}
                    label="身份证背面"
                    name="identityCardBackImg"
                    rules={[{ required: true }]}
                    shouldUpdate
                  >
                    <UploadV2
                      label="替换身份证"
                      maxCount={1}
                      imgCropAspect={3 / 2}
                      id={props.id}
                    />
                  </Form.Item>
                </Col>
              </Row>

              <Divider>
                门店顶部图：图片长宽要求比例为 2:1，最多上传 5 张{" "}
              </Divider>
              <Form.Item name="orgFrontImg" shouldUpdate>
                <UploadV2
                  maxCount={5}
                  imgCropAspect={2}
                  id={props.id}
                  label="门店顶部图"
                />
              </Form.Item>
              <Divider>
                门店室内图：图片长宽要求比例为 2:1，最多上传 5 张{" "}
              </Divider>
              <Form.Item name="orgRoomImg" shouldUpdate>
                <UploadV2
                  maxCount={5}
                  imgCropAspect={2}
                  id={props.id}
                  label="门店室内图"
                />
              </Form.Item>
              <Divider>
                门店其他图：图片长宽要求比例为 2:1，最多上传 5 张{" "}
              </Divider>
              <Form.Item name="orgOtherImg" shouldUpdate>
                <UploadV2
                  maxCount={5}
                  imgCropAspect={2}
                  id={props.id}
                  label="门店其他图"
                />
              </Form.Item>
            </Form>
          </Drawer>
        )}
      </EditStyle>
    );
  }
);

export default Edit;
